//
//  XTComposeTextView.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/20.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit
@IBDesignable
class XTComposeTextView: UITextView {

        //  MARK: -懒加载控件-
    private lazy var placeHolderLabel:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "分享新鲜事"
        label.numberOfLines = 0
        label.textColor = UIColor.lightGrayColor() 
        return label
    }()
    
    //设为占位文字，通过@IBInspectable和@IBDesignable将placeHolderLabel显示在xib的右侧属性栏中
    @IBInspectable var placeHolder:String?{
        didSet{
            placeHolderLabel.text = placeHolder
        }
    }
    
    //重写font的set方法，以保证对textview设置时，placeHolderLabel也跟随改变
    override var font:UIFont?{
        didSet{
            if font == nil{
                return
            }
            
                placeHolderLabel.font = font
        }
 
    }
    
    override var text:String?{
        didSet{
            placeHolderLabel.hidden = hasText()
        }
    
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        //添加监听textView文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        addSubview(placeHolderLabel)
        //系统原生约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute:.Width , multiplier: 1, constant: -10))
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeHolderLabel.x = 5
        placeHolderLabel.y = 8
    }
    @objc private func textChange(){
    
        placeHolderLabel.hidden = hasText()
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}
